<template>
  <div class="app-container main">
    <div style="overflow: auto; height: calc(100% + 0px); box-sizing: border-box;">
      <div class="card_group">
        <div style="width: 100%; border-bottom: 1px solid #ebeef5;">
          <div>
            <el-button type="text" icon="el-icon-folder-add" size="mini" @click="addGroup" style="font-size: 14px;">
              新建分组
            </el-button>
            <el-button type="text" icon="el-icon-folder-add" size="mini" @click="organizeGroups" style="font-size: 14px;">
              整理分组
            </el-button>
          </div>
          <div class="m-b-5">
            <el-popover placement="bottom" width="200" trigger="click" content="分组:">
              <el-select v-model="selectedGroup" size="small" placeholder="请选择">
                <!-- 过滤掉默认分组 -->
                <el-option v-for="group in groups.filter(g => g.value !== 0)" :key="group.value" :label="group.label"
                  :value="group.value">
                </el-option>
              </el-select>
              <el-button type="default" size="small" @click="confirmMove">确定</el-button>
              <el-button type="default" size="small" @click="cancelMove">取消</el-button>
              <el-button type="text" size="mini" slot="reference" style="font-size: 14px;">
                <i class="el-icon-folder-opened"></i> 移动分组
              </el-button>
            </el-popover>
            <el-button type="text" class="ml-10" icon="el-icon-folder-add" size="mini" @click="deleteSelected"
              style="font-size: 14px;">
              删除选中</el-button>
          </div>
          <el-checkbox v-model="selectAll" :indeterminate="isIndeterminate" border size="mini" class="mb8 "
            @change="handleCheckAllChange">全选</el-checkbox>
          <el-dropdown @command="handleCommand">
            <el-button type="primary" size="mini" class="ml-5">
              批量操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="runScript">运行脚本</el-dropdown-item>
              <el-dropdown-item command="reRun">重新运行</el-dropdown-item>
              <el-dropdown-item command="pauseScript">暂停脚本</el-dropdown-item>
              <el-dropdown-item command="resumeScript">恢复运行</el-dropdown-item>
              <el-dropdown-item command="stopScript">停止脚本</el-dropdown-item>
              <!-- <el-dropdown-item command="debugConnect">调试连接</el-dropdown-item> -->
              <el-dropdown-item command="bindScriptConfig">绑定脚本配置</el-dropdown-item>
              <el-dropdown-item command="unbindScriptConfig">取消绑定脚本配置</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div>
          <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" default-expand-all
            :expand-on-click-node="false" @check-change="handleCheckChange"></el-tree>

        </div>
      </div>
      <div style="width: calc(100% - 220px); float: left;">
        <div class="card_key">
          <div class="card_key_hearder">
            <!-- <div class="fl">
              <div class="fl">您的Key为：<span class="bold">C678AF23811F4F4C</span></div>
              <div class="m-l-30 fl">
                <el-switch v-model="keySwitch" active-color="#dcdcdc" inactive-color="#dcdcdc"></el-switch>
                <span>30分钟内免Key</span>
              </div>
              <div class="fr cursor-pointer" style="margin-left: 100px;">
                <el-badge :value="3" class="item">
                  Key功能<i class="el-icon-arrow-down"></i>
                </el-badge>
              </div>
            </div> -->
            <div class="">
              <span class="m-r-10"><i class="flycatico flycat-ico-anzhuo ico-col-brand"
                  style="font-size: 16px; margin-right: 5px;"></i>在线<b class="m-l-5">{{ onlineNum }}</b></span>
              <span class="m-r-10"><i class="flycatico flycat-ico-anzhuo ico-col-info"
                  style="font-size: 16px; margin-right: 5px;"></i>离线<b class="m-l-5">{{ offlineNum }}</b></span>
              <!-- <el-button type="primary" size="mini">设备日志</el-button> -->
            </div>
          </div>
        </div>
        <div class="m-b-5">
          <el-button type="default" size="mini" @click="refresh" style="padding: 4px 10px; font-size: 16px;">
            <i class="el-icon-refresh"></i>
            <span style="font-size: 12px;">({{ countdown }})</span>
          </el-button>
          <span class="span m-l-5">排序</span>
          <el-dropdown>
            <el-button type="mini" style="height: 24px; padding: 4px;" class="m-l-5">
              在线<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="default">默认</el-dropdown-item>
              <el-dropdown-item command="online">在线</el-dropdown-item>
              <el-dropdown-item command="offline">离线</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-divider direction="vertical"></el-divider>
          <span class="span">设备名：</span>
          <el-input v-model="deviceName" size="mini" style="width: 150px;" class="mx-10"></el-input>
          <span class="span">注册码：</span>
          <el-input v-model="registrationCode" size="mini" style="width: 150px;" class="mx-10"></el-input>
          <span class="span">启用：</span>
          <el-select v-model="enabledStatus" size="mini" style="width: 100px;" class="mx-10">
            <el-option label="全部" value="全部"></el-option>
            <el-option label="正常" value="正常"></el-option>
            <el-option label="停用" value="停用"></el-option>
          </el-select>
          <span class="span">脚本状态：</span>
          <el-select v-model="scriptStatus" multiple collapse-tags placeholder="请选择" size="mini" style="width: 150px;"
            class="mx-10">
            <el-option label="全部状态" value="全部状态"></el-option>
            <el-option label="运行中" value="运行中"></el-option>
            <el-option label="暂停中" value="暂停中"></el-option>
            <el-option label="已停止" value="已停止"></el-option>
            <el-option label="启用中" value="启用中"></el-option>
          </el-select>

          <el-button type="primary" size="mini" plain @click="getList">搜索</el-button>
        </div>

        <div style="border-top: 1px solid #dcdcdc;">
          <el-button type="primary" size="mini" @click="addDevice" icon="el-icon-plus"
            style="margin-top: 3px;margin-bottom: 3px;">添加设备</el-button>
          <el-divider direction="vertical"></el-divider>
          <span style="font-size: 13px; color: #666; margin-right: 10px;">批量操作</span>
          <el-button type="text" size="small" @click="deleteSelectedTable" icon="el-icon-delete">删除选中</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popover placement="bottom" width="200" trigger="click" content="分组:">
            <el-select v-model="selectedGroup" size="small" placeholder="请选择">
              <!-- 过滤掉默认分组 -->
              <el-option v-for="group in groups" :key="group.value" :label="group.label" :value="group.value">
              </el-option>
            </el-select>
            <el-button type="default" size="small" @click="moveSelectedTable">确定</el-button>
            <el-button type="default" size="small" @click="cancelMove">取消</el-button>
            <el-button type="text" size="small" slot="reference">
              <i class="el-icon-folder-opened"></i> 移动分组
            </el-button>
          </el-popover>
          <el-divider direction="vertical"></el-divider>

          <el-dropdown @command="handleTableCommand">
            <el-button type="text" size="small">
              运行脚本<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="runScript">运行脚本</el-dropdown-item>
              <el-dropdown-item command="reRun">重新运行</el-dropdown-item>
              <el-dropdown-item command="pauseScript">暂停脚本</el-dropdown-item>
              <el-dropdown-item command="resumeScript">恢复运行</el-dropdown-item>
              <el-dropdown-item command="stopScript">停止脚本</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-divider direction="vertical"></el-divider>

          <el-dropdown @command="handleTableCommand">
            <el-button type="text" size="small">
              调试连接<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="debugConnect">调试连接</el-dropdown-item>
              <el-dropdown-item command="bindScriptConfig">绑定脚本配置</el-dropdown-item>
              <el-dropdown-item command="unbindScriptConfig">取消绑定脚本配置</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>


        <el-table ref="table" :data="tableData" style="width: 100%" size="mini" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="dev_name" label="设备名" sortable></el-table-column>
          <el-table-column prop="pollcode" label="注册码" sortable></el-table-column>
          <el-table-column prop="bindingScriptConfigName" label="已绑定脚本配置" width="150" align="center"
            sortable></el-table-column>
          <el-table-column prop="uname" label="当前账号" align="center" sortable></el-table-column>
          <el-table-column prop="scriptState" label="运行状态" align="center" sortable></el-table-column>
          <el-table-column prop="online" label="状态" align="center" sortable>
            <template slot-scope="scope">
              <el-tag v-if="scope.row.online === '1'" size="mini" type="success">在线</el-tag>
              <el-tag v-else size="mini" type="info">离线</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="version" label="版本号" sortable></el-table-column>
          <el-table-column prop="state" label="启用" sortable>
            <template slot-scope="scope">
              <el-switch :value="scope.row.state === '1'" :active-value="true" :inactive-value="false" readonly>
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="380" align="center" fixed="right">
            <template slot-scope="scope">
              <!-- <el-button type="text" size="mini" @click="remoteControl(scope.row)">远程控制</el-button> -->
              <!-- <el-button type="text" size="mini" @click="registrationCodeAction(scope.row)">注册码</el-button> -->
              <el-button type="text" size="mini" @click="changeData(scope.row)">换号数据</el-button>
              <el-divider direction="vertical"></el-divider>

              <el-button type="text" size="mini" @click="scriptConfig(scope.row)">脚本配置</el-button>
              <el-divider direction="vertical"></el-divider>

              <el-button type="text" size="mini" @click="realNameInfo(scope.row)">实名信息</el-button>
              <el-divider direction="vertical"></el-divider>

              <el-button type="text" size="mini" @click="deleteDevice(scope.row)">删除</el-button>
              <!-- <el-button type="text" size="mini" @click="viewLog(scope.row)">日志</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="2" :page-size="25"
          :page-sizes="[25, 50, 80, 100]"></el-pagination>
      </div>
    </div>
    <!-- 整理分组弹窗 -->
    <el-dialog title="整理分组" :visible.sync="organizeGroupsDialogVisible" width="60%">
      <el-table :data="groupsForOrganize" style="width: 100%">
        <el-table-column prop="groupName" label="分组名称" sortable></el-table-column>
        <el-table-column prop="order" label="排序" sortable></el-table-column>
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-button size="mini" @click="editGroupName(scope.row)">编辑名称</el-button>
            <el-button size="mini" @click="editGroupOrder(scope.row)">编辑排序</el-button>
            <el-button size="mini" type="danger" @click="deleteGroup(scope.row)">删除分组</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="organizeGroupsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrganizeGroups">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 绑定脚本配置弹窗 -->
    <el-dialog title="绑定脚本配置" :visible.sync="bindScriptConfigDialogVisible" width="600px">
      <el-table :data="scriptConfigs" style="width: 100%">
        <el-table-column prop="name" label="配置名" sortable></el-table-column>
        <el-table-column prop="addTime" label="添加时间" sortable></el-table-column>
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" v-if="!scope.row.isBound" @click="bindConfig(scope.row)">
              绑定
            </el-button>
            <el-button type="danger" size="mini" v-else @click="unbindConfig(scope.row)">
              取消绑定
            </el-button>
            <el-button type="info" size="mini" @click="previewSettings(scope.row)">
              预览设置
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bindScriptConfigDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDeviceList,
  addDevice,
  deleteDevice,
  addGroup,
  deleteGroup,
  moveDeviceToGroup,
  batchOperation
} from '@/api/device'
import { getAllConfig, } from "@/api/config.js";

export default {
  data() {
    return {
      selectAll: false,
      isIndeterminate: false,
      selectedGroup: '',
      groups: [], // 从API获取
      treeData: [], // 从API获取
      keySwitch: false,
      tableData: [],
      multipleSelection: [],
      deviceName: '',
      registrationCode: '',
      enabledStatus: '全部',
      scriptStatus: ['全部状态'],
      queryParams: {
        sort: '在线',
        currentPage: 1,
        pagesize: 25,
        total: 0,
        deviceName: '',
        pollcode: '',
        state: '在线',
        scriptState: ['在线'],
        Id: [],
        action: "getDeviceList"
      },
      onlineNum: 0,
      offlineNum: 0,
      treeSelection: [],    // 树形组件选中的设备
      tableSelection: [],   // 表格选中的设备
      loading: false,
      organizeGroupsDialogVisible: false,
      groupsForOrganize: [], // 用于整理分组的临时数据
      countdown: 20, // 倒计时初始值
      countdownInterval: null, // 倒计时定时器
      refreshInterval: 20, // 刷新间隔(秒)
      currentDevice: null, // 当前操作的设备
      bindScriptConfigDialogVisible: false,
      scriptConfigs: [],   // 所有脚本配置列表
      selectedConfigId: null // 当前选中的配置ID
    };
  },
  created() {
    this.getList();
    this.startCountdown(); // 开始倒计时
  },
  beforeDestroy() {
    // 组件销毁前清理定时器
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval);
    }
  },
  computed: {
    // 过滤掉默认分组的分组列表
    groupsWithoutDefault() {
      // 假设默认分组的ID为0或者是名称为"默认分组"
      return this.groups.filter(group => {
        // 根据实际情况调整判断条件
        // 如果默认分组有特定ID
        return group.value !== 0 && group.label !== '默认分组';
        // 或者根据你的业务逻辑判断哪个是默认分组
      });
    }
  },
  methods: {
    getList() {
      this.loading = true;
      this.queryParams.deviceName = this.deviceName;
      this.queryParams.pollcode = this.registrationCode;
      this.queryParams.state = this.enabledStatus === '全部' ? '' : this.enabledStatus;
      this.queryParams.scriptState = this.scriptStatus.includes('全部状态') ? [] : this.scriptStatus;

      getDeviceList(this.queryParams).then(response => {
        this.loading = false;
        if (response.Code == 200) {
          // 保存完整数据用于左侧树显示
          this.allGroups = response.Data.group || [];
          this.allDevices = response.Data.Data || [];

          // 设置表格数据（搜索过滤后的）
          this.tableData = this.allDevices;

          // 构建分组下拉列表数据（过滤掉默认分组）
          this.groups = this.allGroups
            .filter(group => group.Id !== 0 && group.groupName !== '默认分组') // 过滤掉默认分组
            .map(group => ({
              value: group.Id,
              label: group.groupName
            }));

          // 构建树形数据（显示所有分组，包括默认分组）
          this.treeData = this.allGroups
            .map(group => ({
              id: `group_${group.Id}`,
              label: `${group.groupName}(${group.device.length})`,
              children: group.device.map(device => ({
                id: device.Id,
                label: device.dev_name,
                // 添加原始数据用于搜索过滤
                rawData: device
              }))
            }));

          // 如果是搜索状态，只勾选匹配的设备
          this.$nextTick(() => {
            if (this.isSearching()) {
              // 获取搜索到的设备ID
              const searchedDeviceIds = this.tableData.map(item => item.id);
              this.$refs.tree.setCheckedKeys(searchedDeviceIds);
            } else {
              // 非搜索状态，勾选所有设备
              const allDeviceIds = this.getAllDeviceIds();
              this.$refs.tree.setCheckedKeys(allDeviceIds);
            }
          });
        }
      });
    },



    // 新增方法：判断是否在搜索状态
    isSearching() {
      return this.deviceName ||
        this.registrationCode ||
        this.enabledStatus !== '全部' ||
        !this.scriptStatus.includes('全部状态');
    },


    getAllDeviceIds() {
      // 只获取非默认分组中的设备ID
      return this.treeData.reduce((ids, group) => {
        if (group.children && group.children.length) {
          return [...ids, ...group.children.map(device => device.id)]
        }
        return ids
      }, [])
    },

    handleCheckChange(data, checked, indeterminate) {
      this.isIndeterminate = indeterminate;
      this.selectAll = checked;

      // 获取当前选中的设备ID
      const checkedKeys = this.$refs.tree.getCheckedKeys();

      // 过滤表格数据，只显示选中的设备
      this.tableData = this.allDevices.filter(device =>
        checkedKeys.includes(device.id)
      );
    },

    // 新增方法：更新选中的设备列表
    updateSelectedDevices() {
      if (this.$refs.tree) {
        const checkedKeys = this.$refs.tree.getCheckedKeys();
        const checkedNodes = this.$refs.tree.getCheckedNodes();

        this.multipleSelection = checkedNodes
          .filter(node => !node.children) // 只保留设备节点（叶子节点）
          .map(node => ({
            id: node.id,
            deviceName: node.label
          }));

        // 根据选中的设备ID查询数据
        this.querySelectedDevices(checkedKeys);
      }
    },

    // 新增方法：查询选中的设备
    querySelectedDevices(deviceIds) {
      if (deviceIds.length === 0) {
        this.tableData = [];
        return;
      }

      this.queryParams.Id = deviceIds;
      getDeviceList(this.queryParams).then(response => {
        if (response.Code == 200) {
          this.tableData = response.Data.Data || 0

          // 保持表格原有选中状态
          this.$nextTick(() => {
            this.tableData.forEach(row => {
              const isSelected = this.tableSelection.some(
                sel => sel.id === row.id
              );
              this.$refs.table.toggleRowSelection(row, isSelected);
            });
          });
        }
      });
    },
    // 添加分组
    addGroup() {
      this.$prompt('请输入分组名称', '新建分组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value) {
            return '分组名称不能为空';
          }
        }
      }).then(({ value }) => {
        addGroup({
          group_name: value,
          action: 'addGroup'
        }).then(response => {
          if (response.Code === 200) {
            this.$message.success('分组添加成功');
            this.getList();
          } else {
            this.$message.error(response.Msg);
          }
        });
      }).catch(() => {
        // 用户取消
      });
    },

    // 打开整理分组弹窗
    organizeGroups() {
      this.organizeGroupsDialogVisible = true;
      // 过滤掉默认分组
      this.groupsForOrganize = this.allGroups
        .filter(group => group.Id !== 0 && group.groupName !== '默认分组') // 过滤掉默认分组
        .map(group => ({
          id: group.Id,
          groupName: group.groupName,
          order: group.order || 0
        }));
    },
    // 编辑分组名称
    editGroupName(row) {
      this.$prompt('请输入新的分组名称', '编辑名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row.groupName
      }).then(({ value }) => {
        row.groupName = value;
        this.updateGroup(row, 'groupName');
      }).catch(() => {
        // 用户取消
      });
    },

    // 编辑分组排序
    editGroupOrder(row) {
      this.$prompt('请输入新的排序值', '编辑排序', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: row.order.toString()
      }).then(({ value }) => {
        row.order = parseInt(value);
        this.updateGroup(row, 'order');
      }).catch(() => {
        // 用户取消
      });
    },
    // 更新分组信息（名称或排序）
    updateGroup(row, field) {
      const params = {
        id: row.id,
        [field]: row[field],
        action: `updateGroup${field.charAt(0).toUpperCase()}${field.slice(1)}`
      };
      updateGroup(params).then(response => {
        if (response.Code === 200) {
          this.$message.success('更新成功');
        } else {
          this.$message.error(response.Msg);
        }
      });
    },
    // 删除分组
    deleteGroup(row) {
      this.$confirm(`确定要删除分组 "${row.groupName}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteGroupById(row.id);
      }).catch(() => {
        // 用户取消
      });
    },

    // 保存整理分组结果
    saveOrganizeGroups() {
      // 这里可以发送所有分组的新排序到后端批量更新
      const updatePromises = this.groupsForOrganize.map(group => {
        return this.updateGroup(group, 'order');
      });

      Promise.all(updatePromises).then(() => {
        this.$message.success('分组排序保存成功');
        this.organizeGroupsDialogVisible = false;
        this.getList(); // 刷新数据
      });
    },

    // 确认移动分组 - 左边按钮（操作树形组件勾选的设备）
    confirmMove() {
      if (!this.selectedGroup) {
        this.$message.warning('请选择目标分组');
        return;
      }

      // 获取树形组件勾选的设备
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      if (checkedKeys.length === 0) {
        this.$message.warning('请选择要移动的设备');
        return;
      }

      // 确保发送的是数组格式
      const deviceIds = Array.isArray(checkedKeys) ? checkedKeys : [checkedKeys];
      moveDeviceToGroup({
        device_id: deviceIds, // 发送数组
        group_id: this.selectedGroup,
        action: 'moveDeviceToGroup'
      }).then(response => {
        if (response.Code === 200) {
          this.$message.success('移动分组成功');
          this.getList();
        } else {
          this.$message.error(response.Msg);
        }
      });
    },

    // 取消移动分组
    cancelMove() {
      this.selectedGroup = '';
    },

    // 删除选中设备 - 左边按钮（操作树形组件勾选的设备）
    deleteSelected() {
      // 获取树形组件勾选的设备
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      if (checkedKeys.length === 0) {
        this.$message.warning('请选择要删除的设备');
        return;
      }

      this.$confirm('确定要删除选中的设备吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deviceIds = checkedKeys;
        deleteDevice({
          ids: deviceIds,
          action: 'deleteDevice'
        }).then(response => {
          if (response.Code === 200) {
            this.$message.success('删除成功');
            this.getList();
          } else {
            this.$message.error(response.Msg);
          }
        });
      }).catch(() => {
        // 用户取消
      });
    },

    // 右边的删除选中设备（操作表格勾选的设备）
    deleteSelectedTable() {
      if (this.tableSelection.length === 0) {
        this.$message.warning('请选择要删除的设备');
        return;
      }

      this.$confirm('确定要删除选中的设备吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deviceIds = this.tableSelection.map(item => item.id);
        deleteDevice({
          ids: deviceIds,
          action: 'deleteDevice'
        }).then(response => {
          if (response.Code === 200) {
            this.$message.success('删除成功');
            this.getList();
          } else {
            this.$message.error(response.Msg);
          }
        });
      }).catch(() => {
        // 用户取消
      });
    },

    // 右边的移动分组（操作表格勾选的设备）
    moveSelectedTable() {
      if (!this.selectedGroup) {
        this.$message.warning('请选择目标分组');
        return;
      }

      if (this.tableSelection.length === 0) {
        this.$message.warning('请选择要移动的设备');
        return;
      }

      // 确保发送的是数组格式
      const deviceIds = this.tableSelection.map(item => item.id);
      moveDeviceToGroup({
        device_id: deviceIds,
        group_id: this.selectedGroup,
        action: 'moveDeviceToGroup'
      }).then(response => {
        if (response.Code === 200) {
          this.$message.success('移动分组成功');
          this.getList();
        } else {
          this.$message.error(response.Msg);
        }
      });
    },

    // 批量操作 - 左边（操作树形组件勾选的设备）
    handleCommand(command) {
      // 获取树形组件勾选的设备
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      if (checkedKeys.length === 0) {
        this.$message.warning('请选择要操作的设备');
        return;
      }

      const deviceIds = checkedKeys;

      switch (command) {
        case 'runScript':
        case 'reRun':
        case 'pauseScript':
        case 'resumeScript':
        case 'stopScript':
        case 'debugConnect':
          batchOperation({
            command,
            device_ids: deviceIds,
            action: 'batchOperation'
          }).then(response => {
            if (response.Code === 200) {
              this.$message.success('操作成功');
              this.getList();
            } else {
              this.$message.error(response.Msg);
            }
          });
          break;

        case 'bindScriptConfig':
          this.handleBindScriptConfig(deviceIds);
          break;

        case 'unbindScriptConfig':
          batchOperation({
            command,
            device_ids: deviceIds,
            action: 'batchOperation'
          }).then(response => {
            if (response.Code === 200) {
              this.$message.success('取消绑定成功');
              this.getList();
            } else {
              this.$message.error(response.Msg);
            }
          });
          break;

        default:
          this.$message.warning('未知操作命令');
      }
    },


    // 全选/取消全选
    handleCheckAllChange(val) {
      if (this.$refs.tree) {
        if (val) {
          // 全选所有设备节点（不包括默认分组中的设备）
          this.$refs.tree.setCheckedKeys(this.getAllDeviceIds());
        } else {
          this.$refs.tree.setCheckedKeys([]);
        }
      }
      this.isIndeterminate = false;
    },

    // 批量操作
    handleCommand(command) {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要操作的设备');
        return;
      }

      const deviceIds = this.multipleSelection.map(item => item.id);

      switch (command) {
        case 'runScript':
        case 'reRun':
        case 'pauseScript':
        case 'resumeScript':
        case 'stopScript':
        case 'debugConnect':
          batchOperation({
            command,
            device_ids: deviceIds,
            ...extraParams,
            action: 'batchOperation'
          }).then(response => {
            if (response.Code === 200) {
              this.$message.success('操作成功');
              this.getList();
            } else {
              this.$message.error(response.Msg);
            }
          });
          break;

        case 'bindScriptConfig':
          this.handleBindScriptConfig(deviceIds);
          break;

        case 'unbindScriptConfig':
          batchOperation(command, deviceIds).then(response => {
            if (response.Code === 200) {
              this.$message.success('取消绑定成功');
              this.getList();
            } else {
              this.$message.error(response.Msg);
            }
          });
          break;

        default:
          this.$message.warning('未知操作命令');
      }
    },

    // 右边的批量操作（操作表格勾选的设备）
    handleTableCommand(command) {
      if (this.tableSelection.length === 0) {
        this.$message.warning('请选择要操作的设备');
        return;
      }

      const deviceIds = this.tableSelection.map(item => item.id);

      switch (command) {
        case 'runScript':
        case 'reRun':
        case 'pauseScript':
        case 'resumeScript':
        case 'stopScript':
        case 'debugConnect':
          batchOperation({
            command,
            device_ids: deviceIds,
            action: 'batchOperation'
          }).then(response => {
            if (response.Code === 200) {
              this.$message.success('操作成功');
              this.getList();
            } else {
              this.$message.error(response.Msg);
            }
          });
          break;

        case 'bindScriptConfig':
          this.handleBindScriptConfig(deviceIds);
          break;

        case 'unbindScriptConfig':
          batchOperation({
            command,
            device_ids: deviceIds,
            action: 'batchOperation'
          }).then(response => {
            if (response.Code === 200) {
              this.$message.success('取消绑定成功');
              this.getList();
            } else {
              this.$message.error(response.Msg);
            }
          });
          break;

        default:
          this.$message.warning('未知操作命令');
      }
    },

    // 处理绑定脚本配置
    handleBindScriptConfig(deviceIds) {
      this.$prompt('请输入脚本配置ID和名称', '绑定脚本配置', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '先输入ID,然后输入名称，用逗号分隔',
        inputValidator: (value) => {
          if (!value || value.split(',').length !== 2) {
            return '请输入正确的脚本配置ID和名称，用逗号分隔';
          }
        }
      }).then(({ value }) => {
        const [script_config_id, script_config_name] = value.split(',');
        batchOperation({
          command: 'bindScriptConfig',
          device_ids: deviceIds,
          script_config_id: parseInt(script_config_id),
          script_config_name,
          action: 'batchOperation'
        }).then(response => {
          if (response.Code === 200) {
            this.$message.success('绑定成功');
            this.getList();
          } else {
            this.$message.error(response.Msg);
          }
        });
      }).catch(() => {
        // 用户取消
      });
    },

    // 表格选择变化
    handleSelectionChange(val) {
      this.tableSelection = val;
    },

    // 树形组件勾选变化时更新multipleSelection用于左边的批量操作
    handleCheckChange(data, checked, indeterminate) {
      this.isIndeterminate = indeterminate;
      // 获取当前选中的设备ID用于左边的批量操作
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      this.multipleSelection = checkedKeys.map(id => ({ id }));
    },



    // 刷新数据
    refresh() {
      this.getList();
    },

    // 添加设备
    addDevice() {
      this.$prompt('请输入设备名称', '添加设备', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value) {
            return '设备名称不能为空';
          }
        }
      }).then(({ value }) => {
        addDevice({
          dev_name: value,
          action: 'addDevice'
        }).then(response => {
          if (response.Code === 200) {
            this.$message.success('设备添加成功');
            this.getList();
          } else {
            this.$message.error(response.Msg);
          }
        });
      }).catch(() => {
        // 用户取消
      });
    },

    // 运行脚本
    runScript() {
      this.handleCommand('runScript');
    },

    // 重新运行
    reRun() {
      this.handleCommand('reRun');
    },

    // 暂停脚本
    pauseScript() {
      this.handleCommand('pauseScript');
    },

    // 恢复运行
    resumeScript() {
      this.handleCommand('resumeScript');
    },

    // 停止脚本
    stopScript() {
      this.handleCommand('stopScript');
    },

    // 调试连接
    debugConnect() {
      this.handleCommand('debugConnect');
    },

    // 绑定脚本配置
    bindScriptConfig() {
      this.handleCommand('bindScriptConfig');
    },

    // 取消绑定脚本配置
    unbindScriptConfig() {
      this.handleCommand('unbindScriptConfig');
    },
    // 绑定配置
    bindConfig(config) {
      if (this.currentDevice.bindingScriptConfigId) {
        this.$message.warning('该设备已绑定其他配置，请先取消绑定！');
        return;
      }

      batchOperation({
        command: 'bindScriptConfig',
        device_ids: [this.currentDevice.id],
        script_config_id: config.id,
        script_config_name: config.name,
        action: 'batchOperation'
      }).then(response => {
        if (response.Code === 200) {
          this.$message.success('绑定成功');
          this.currentDevice.bindingScriptConfigId = config.id; // 更新本地数据
          this.bindScriptConfigDialogVisible = false;
          this.getList(); // 刷新列表
        } else {
          this.$message.error(response.Msg);
        }
      });
    },

    // 取消绑定
    unbindConfig(config) {
      batchOperation({
        command: 'unbindScriptConfig',
        device_ids: [this.currentDevice.id],
        action: 'batchOperation'
      }).then(response => {
        if (response.Code === 200) {
          this.$message.success('取消绑定成功');
          this.currentDevice.bindingScriptConfigId = null;
          this.bindScriptConfigDialogVisible = false;
          this.getList();
        } else {
          this.$message.error(response.Msg);
        }
      });
    },
    // 表格选择变化
    handleSelectionChange(val) {
      this.tableSelection = val;
    },

    // 删除单个设备
    deleteDevice(row) {
      this.$confirm(`确定要删除设备 "${row.deviceName}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice({
          ids: [row.id],
          action: 'deleteDevice'

        }).then(response => {
          if (response.Code === 200) {
            this.$message.success('删除成功');
            this.getList();
          } else {
            this.$message.error(response.Msg);
          }
        });
      }).catch(() => {
        // 用户取消
      });
    },

    // 换号数据
    changeData(row) {
      this.$message.info(`换号数据功能开发中，设备ID: ${row.id}`);
    },

    // 脚本配置
    scriptConfig(row) {
      this.currentDevice = row; // 记录当前设备
      this.bindScriptConfigDialogVisible = true;
      this.loadScriptConfigs(); // 加载所有脚本配置
    },
    loadScriptConfigs() {
      getAllConfig({ search: this.searchText, page: this.currentPage, pageSize: this.pageSize }).then(res => {
        this.scriptConfigs = res.Data.map(config => ({
          id: config.id,
          name: config.name,
          addTime: config.addTime,
          isBound: config.id === this.currentDevice.bindingScriptConfigId // 是否已绑定
        }));
      });
    },
    // 实名信息
    realNameInfo(row) {
      this.$message.info(`实名信息功能开发中，设备ID: ${row.id}`);
    },
    // 开始倒计时
    startCountdown() {
      // 如果已有定时器，先清理
      if (this.countdownInterval) {
        clearInterval(this.countdownInterval);
      }

      // 重置倒计时
      this.countdown = this.refreshInterval;

      // 启动新的倒计时
      this.countdownInterval = setInterval(() => {
        this.countdown--;

        // 倒计时结束
        if (this.countdown <= 0) {
          this.refresh(); // 刷新数据
          this.countdown = this.refreshInterval; // 重置倒计时
        }
      }, 1000);
    },

    // 刷新数据
    refresh() {
      this.getList();
      // 重置倒计时
      this.countdown = this.refreshInterval;
    },
  }
};
</script>

<style scoped>
/* 根据需要添加样式 */
.card_group {
  width: 190px;
  float: left;
  /* color: #444; */
  /* height: calc(100% - 80px); */
  height: 100%;
  border-right: 1px solid #dcdfe6;
  margin-right: 10px;
  padding: 0 10px 10px 0;
  font-size: 12px !important;
}

.card_key {
  color: #444;
  box-sizing: border-box;
  background-color: rgb(243, 248, 254);
  /* height: 400px; */
  border-radius: 6px;
  font-size: 12px !important;
  margin-bottom: 10px;
}

.card_key>.card_key_hearder {
  max-width: 800px;
}

.card_key>.card_key_hearder {
  height: 40px;
  padding: 0 20px;
  line-height: 40px;
}

.span {
  font-size: 13px;
  color: #606266;
}

::v-deep .el-button {
  font-weight: normal;
}
</style>